package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


/**
 * 模拟判断是否登录
 */
@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
//        return "pre";  前置过滤器  一般自定义的过滤器都用前置过滤器
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
//        return false;
        //调用商品检查权限

        //调用用户贺订单不检查权限

        //判断当前请求调用的是否是item-service

        RequestContext currentContext = RequestContext.getCurrentContext();
        String serviceId =(String)  currentContext.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equals(serviceId);
    }


    @Override
    public Object run() throws ZuulException {
//        return null;
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)){
            currentContext.setSendZuulResponse(false);

            String json = JsonResult.err().code(JsonResult.NOT_LOGIN).msg("未登录").toString();
            currentContext.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
            currentContext.setResponseBody(json);
        }
        //在当前zuul版本中，这个返回值没有任何作用
        return null;
    }
}
